/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-07-09     82752       the first version
 */
#ifndef SRC_LORA_NET_MANAGER_H_
#define SRC_LORA_NET_MANAGER_H_

#include <rtthread.h>
#include "common.h"
#include "lora_as32.h"
#include "cJSON.h"

#define LORA_NET             0xF1

#define UNLINK_COUNT         5
#define CHECK_ONLINE_PERIOD  10
#define MAX_LORA_NODE                32

typedef enum {
    TEMPERATURE = 0,
    HUMID,
    TEMP_WITH_HUMID,
    LIGHT

} sensor_type_t;

typedef enum {
    LED = 0x10,

} module_type_t;


typedef enum {
    LEN_POS_IN_LORA_NET_PACK = 0,
    SRC_ADDRH_POS_IN_LORA_NET_PACK,
    SRC_ADDRL_POS_IN_LORA_NET_PACK,
    SRC_CHAN_POS_IN_LORA_NET_PACK,
    CMDH_POS_IN_LORA_NET_PACK,
    CMDL_POS_IN_LORA_NET_PACK,
    DATA_START_POS_IN_LORA_NET_PACK
} lora_net_pack_pos_t;

typedef enum {
    LORA_NET_CMD_GET_NODE_DATA,
    LORA_NET_CMD_REPORT_NODE_DATA,

    LORA_NET_CMD_NODE_DATA_START_TIMING_REPORT,
    LORA_NET_CMD_NODE_DATA_STOP_TIMING_REPORT,

    LORA_NET_CMD_NODE_CONTROL,

    LORA_NET_CONNECT,
    LORA_NET_RECONNECT,
    LORA_NET_HEARTBEAT,

    LORA_NET_CONNECT_OK_ACK

} lora_net_induction_t;

typedef struct lora_node {
    uint8_t  status;
    uint8_t  unlink_count;
    uint16_t addr;

    struct rt_list_node entry;
} lora_node_t;

typedef struct lora_node_list_opt {

    int (*lora_node_list_init)(struct rt_list_node **head);
    int (*add_lora_node)(struct rt_list_node *head, struct lora_node *ln);
    int (*delete_lora_node)(struct rt_list_node *head, uint16_t naddr);
    int (*get_lora_node_addr_list)(struct rt_list_node *head, uint16_t *addr_array);
    lora_node_t *(*get_lora_node_from_addr)(struct rt_list_node *head, uint16_t naddr);

} lora_node_list_opt_t;

typedef void (*get_node_data_callback_t)(uint16_t addr, uint8_t *data, uint8_t len);

typedef struct lora_net_manager {

    volatile uint8_t lora_net_update_flag;

    rt_device_t lora_dev;

    rt_list_t *lora_node_list_head;
    struct lora_node_list_opt *opt;
    struct rt_timer heartbeat_timer;
    struct rt_mutex lora_list_mutex;

    struct rt_thread lnm_thread;

    struct rt_work update_lora_net_work;

    void (*get_node_data_callback)(uint16_t addr, uint8_t *data, uint8_t len);
} lora_net_manager_t;

int lora_net_manager_init(rt_device_t lora_dev,  get_node_data_callback_t callback);
int is_lora_node_addr_in_net(uint16_t addr);

#endif /* SRC_LORA_NET_MANAGER_H_ */
